'''
爬虫
'''
import hashlib
import urllib
import random
import string
import requests
from lxml.html.defs import list_tags
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
import time
import json
import base64
import io
from PIL import Image
import os
import uuid
from db.mysql_server import CvvImgData
from db.redis_server import get_redis
from ip_config import SimpleProxyPool
import pickle
import js_inject
from constant import *
from selenium.webdriver.common.proxy import Proxy, ProxyType


redis = get_redis()
simple_proxy = SimpleProxyPool(url="http://api.shenlongproxy.com/ip?cty=JP&c=10&pt=1&ft=json&pat=\n&rep=1&key=fd86c71b&ts=6")
#captcha = "https://api.yescaptcha.com/createTask"
captcha = "https://api.capsolver.com/createTask"
captcha_key = "CAP-147149A8FD7E82B0A83BCD2E317C51AB2D5060780317C5C0488E4DBBFF596609"


def save_cookies(driver, filename="cookies.pkl"):
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    cookies = driver.get_cookies()
    with open(filename, 'wb') as f:
        pickle.dump(cookies, f)
    print(f"已保存 {len(cookies)} 个cookies")


def load_cookies(driver, filename="cookies.pkl"):
    if not os.path.exists(filename):
        return False

    with open(filename, 'rb') as f:
        cookies = pickle.load(f)

    # 必须先访问域名才能设置cookie
    driver.get("https://manatuku.com")

    for cookie in cookies:
        try:
            driver.add_cookie(cookie)
        except Exception as e:
            print(f"添加cookie失败: {e}")

    print(f"已加载 {len(cookies)} 个cookies")
    return True


def get_api_responses(driver, filter_pattern=None, method_filter=None):
    """获取拦截的 API 响应"""
    all_responses = driver.execute_script("return window.__apiResponses;")

    filtered_responses = all_responses
    if filter_pattern:
        filtered_responses = [r for r in filtered_responses if filter_pattern in r['url']]
    if method_filter:
        filtered_responses = [r for r in filtered_responses if r['method'].upper() == method_filter.upper()]

    return filtered_responses


def clear_api_responses(driver):
    """清空之前的响应记录"""
    driver.execute_script("window.__apiResponses = [];")


def get_api_captcha(img_list: list, questions: list):
    question = "aws:grid:" + ":".join(questions)

    proxies = {'https': 'http://127.0.0.1:7897'}

    query = {
        'clientKey': captcha_key,
        'task': {
            'type': "AwsWafClassification",
            'websiteURL': "https://manatuku.com/payments/new",
            'question': question,
            'images': img_list
        }
    }
    result_json = requests.post(url=captcha, json=query, proxies=proxies, verify=False, timeout=10)
    json_data = json.loads(result_json.text)
    solution = json_data["solution"]
    return solution["objects"]


def exist_img(img_hash):
    img_data = redis.get_cached(img_hash)
    if img_data:
        return img_data
    else:
        img = CvvImgData.select().where(CvvImgData.img_hash == img_hash).execute()
        if img:
            return img
    return None


def save_img(img_hash, img_path, result):
    CvvImgData.create(img_hash=img_hash,
                      img_path=img_path, result=result).save()


def get_login_data():
    datas = []
    data = {
        "email": "1181161519@qq.com",
        "passwd": "123456"
    }
    datas.append(data)
    return datas


def get_email(domain=None, username_length=8):
    # 生成随机用户名（字母+数字）
    username_chars = string.ascii_lowercase + string.digits
    username = ''.join(random.choices(username_chars, k=username_length))

    # 选择域名
    if domain:
        # 如果指定了域名，使用指定的域名
        email_domain = domain
    else:
        # 否则从常用域名中随机选择
        email_domain = random.choice(common_domains)

    # 组合成完整邮箱地址
    email = f"{username}@{email_domain}"

    return email


def simple_password(length=8, use_uppercase=True, use_lowercase=True, use_digits=True):
    """简单的随机字符串生成器"""
    chars = ""
    if use_uppercase:
        chars += string.ascii_uppercase
    if use_lowercase:
        chars += string.ascii_lowercase
    if use_digits:
        chars += string.digits

    # 如果没有任何字符类型被选择，默认使用所有
    if not chars:
        chars = string.ascii_letters + string.digits

    return ''.join(random.choice(chars) for _ in range(length))


def handle_captcha_with_selenium():
    os.makedirs("../img", exist_ok=True)
    options = webdriver.ChromeOptions()
    ip_port = simple_proxy.get_next_proxy()
    options.add_argument('--proxy-server=' + "https://" + ip_port['ip'] + ":" + str(ip_port['port']))
    options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
    options.add_argument('--lang=ja-JP')
    options.add_argument("--start-maximized")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    options.add_argument("--disable-blink-features=AutomationControlled")
    service = Service(executable_path="E:\deleloptool\chromedriver-win64\chromedriver.exe")
    options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})
    #proxy = Proxy()
    #proxy.proxy_type = ProxyType.MANUAL
    #proxy.http_proxy = "https://novada309zkB_ynaP3U-zone-resi-region-jp:wMiwCpuXV5he@24fd2a4e70b435d6.xji.na.novada.pro:7777"
    #proxy.ssl_proxy = "https://novada309zkB_ynaP3U-zone-resi-region-jp:wMiwCpuXV5he@24fd2a4e70b435d6.xji.na.novada.pro:7777"

    #capabilities = webdriver.DesiredCapabilities.CHROME
    #proxy.add_to_capabilities(capabilities)
    driver = webdriver.Chrome(options=options, service=service)
    # 设置语言
    driver.execute_cdp_cmd("Network.setExtraHTTPHeaders", {
        "headers": {
            "Accept-Language": "ja-JP,ja;q=0.9,en;q=0.8"
        }
    })

    # 设置时区
    driver.execute_cdp_cmd("Emulation.setTimezoneOverride", {
        "timezoneId": "Asia/Tokyo"
    })

    # 设置用户代理（可选）
    driver.execute_cdp_cmd("Network.setUserAgentOverride", {
        "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    })

    # 设置屏幕分辨率（可选）
    driver.execute_cdp_cmd("Emulation.setDeviceMetricsOverride", {
        "width": 1920,
        "height": 1080,
        "deviceScaleFactor": 1,
        "mobile": False
    })
    try:
        # 访问目标URL
        driver.get("https://manatuku.com/payments/new")
        #driver.get("https://manatuku.com/customers/sign_up")

        wait = WebDriverWait(driver, 10)

        captcha_frame = wait.until(
            EC.presence_of_element_located((By.ID, "amzn-captcha-verify-button"))
        )
        driver.execute_script(js_inject.intercept_script)
        captcha_frame.click()
        print("检测到CAPTCHA验证")

        time.sleep(3)

        # 获取接口返回值
        responses = get_api_responses(driver)
        for response in responses:
            print("=" * 50)
            print(f"接口URL: {response['url']}")
            print(f"请求方法: {response['method']}")
            print(f"状态码: {response['status']}")
            print(f"请求类型: {response['type']}")
            print(f"请求体: {response['requestBody']}")

            try:
                # 尝试解析 JSON 响应
                response_data = json.loads(response['response'])
                print("JSON 响应:")
                response_json = json.dumps(response_data, indent=2, ensure_ascii=False)
                print(response_json)
                json_response = json.loads(response_json)
                if "assets" in json_response:
                    assets = json_response['assets']

                    images = assets['images']
                    img_list = json.loads(images)
                    print("size:", len(img_list))
                    clear_api_responses(driver)
                    new_img_list = []
                    for  img in img_list:
                        new_img_list.append(img)
                    question = assets["target"]
                    print(question)
                    questions = json.loads(question)
                    captcha_list = get_api_captcha(new_img_list, questions)
                    print(captcha_list)
                    for index, num in enumerate(captcha_list):
                        # 使用XPath定位包含特定文本的按钮
                        img_index = num + 1
                        xpath = f"//canvas//button[text()='{img_index}']"

                        try:
                            button = WebDriverWait(driver, 10).until(
                                EC.presence_of_element_located((By.XPATH, xpath))
                            )
                            # 使用JavaScript点击，绕过交互性检查
                            driver.execute_script("arguments[0].click();", button)
                            print(f"已通过JS点击图片 {img_index}")
                            if img_index % 3 == 0:
                                time.sleep(1)
                            else:
                                time.sleep(0.5)

                        except Exception as e:
                            print(f"点击图片 {img_index} 失败: {e}")
                    clear_api_responses(driver)

                    #<button type="submit" id="amzn-btn-verify-internal" class="btn btn-primary" style="display: block;">确认</button>
                    waiting = WebDriverWait(driver, 10).until(
                        EC.presence_of_element_located((By.ID, "amzn-btn-verify-internal"))
                    )

                    waiting.click()
                    time.sleep(10)


                    waiting_login = WebDriverWait(driver, 10).until(
                           EC.element_to_be_clickable((By.ID, "amzn-btn-verify-internal"))
                     )

                    waiting_login.clear()
                    email_ = get_email()
                    waiting_login.send_keys(email_)
                    waiting_email = WebDriverWait(driver, 10).until(
                        EC.element_to_be_clickable((By.ID, "amzn-btn-verify-internal"))
                    )
                    waiting_email.clear()
                    password_ = simple_password()
                    waiting_email.send_keys(password_)
                    # 登录
                    driver.find_element(By.ID, "amzn-btn-verify-internal").click()
                    # 判断页面是否出现了人类认证

                    break

            except json.JSONDecodeError:
                print("响应文本:", response['response'])

            print(f"时间戳: {response['timestamp']}")

    except Exception as e:
        print(f"处理CAPTCHA时出错: {e}")
        driver.quit()
    #finally:


if __name__ == "__main__":
    handle_captcha_with_selenium()
    #test_api()
